//
//  RenwuViewController.m
//  penzer
//
//  Created by caiyc on 2018/10/18.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "RenwuViewController.h"
#import "RenwuCell.h"
#import "RenwuDetailViewController.h"

@interface RenwuViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UIButton *rightBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIScrollView *topScrollView;
@property (nonatomic,strong) NSMutableArray<UIButton *> *topBtns;
@property (nonatomic,weak) UIView *indicatorBar;
@property (nonatomic,strong) UIButton *last_btn;

@property (nonatomic,strong) NSArray *taskCategory;
@property (nonatomic,strong) NSMutableDictionary<NSString*,NSArray*> *taskList;
@property (nonatomic,assign) NSInteger type_index;


@end

@implementation RenwuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self setNavigation:1 andTitle:@"任务中心" andNaviColor:[UIColor whiteColor] andTitleColor:nil];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    // Do any additional setup after loading the view from its nib.
    self.topScrollView.backgroundColor = [UIColor whiteColor];
    self.topScrollView.showsHorizontalScrollIndicator = NO;
    [self setupRightBtn];
    [self fetchTaskCategory];
}


- (void)setupRightBtn
{
    UIButton *btn = [UIButton new];
    _rightBtn = btn;
    [btn setTitle:@"经验总值：400" forState:UIControlStateNormal];
    [btn setTitleColor:RZ_COLOR(154, 154, 154) forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Light" size:15];
    [self.naviView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.navigationController.navigationBar.height);
        make.bottom.equalTo(self.naviView);
        make.right.mas_equalTo(-20);
    }];
}



- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self setupTopViewFrame];
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.taskList[@(self.type_index).stringValue].count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellId = @"cell";
    RenwuCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
    if(!cell){
        cell = [[[NSBundle mainBundle]loadNibNamed:@"RenwuCell" owner:self options:nil]lastObject];
    }
    NSDictionary *dict = self.taskList[@(self.type_index).stringValue][indexPath.row];
    if(dict){
        cell.title.text = dict[@"title"];
        cell.desc.text = [NSString stringWithFormat:@"经验值+%@",dict[@"exp"]];
    }
    
    return cell;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = self.taskList[@(self.type_index).stringValue];
    if(indexPath.row < arr.count){
        NSDictionary *dict = arr[indexPath.row];
        RenwuDetailViewController *detail = [[RenwuDetailViewController alloc] initWithTask_id:dict[@"id"]];
        [self pushSecondVC:detail];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark--获取分类数据
- (void)fetchTaskCategory
{
    HelenParametersDic *dict = [HelenParametersDic h_dictionary];
    /**
     http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=member&op=task&m=bz_activities&token=87ffec5d746e139250f2da176caff727&ta=get_category

     */
    dict[@"ctrl"] = @"live";
    dict[@"ac"] = @"member";
    dict[@"op"] = @"task";
    dict[@"ta"] = @"get_category";
    dict[@"token"] = [RZ_USERDEFAULTES objectForKey:USER_INFO][@"token"];
    
    [HelenHttpClient requestWithUrlString:BASE_URL andParam:dict andMethod:@"POST" progress:nil success:^(id responseObject) {
        
        NSDictionary *res = responseObject[@"message"];
        NSInteger code = [res[@"resultCode"] integerValue];
        if(code== 0 || code ==1){
            self.taskCategory = res[@"data"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setupTopScorllview];
                if(self.taskCategory.count > 0){
                    NSString *expStr = [NSString stringWithFormat:@"经验总值：%@",self.taskCategory.firstObject[@"sum_exp"]];
                    [self.rightBtn setTitle:expStr forState:UIControlStateNormal];
                }
            });
        }
        
    } andFailBlock:^(NSInteger ErrorCode, NSError *ErrorString) {
        
    }];
}




- (void)setupTopScorllview
{
    [self.taskCategory enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = [UIButton new];
        NSString *title = [NSString stringWithFormat:@"%@ %@",obj[@"title"],obj[@"task_num"]];
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitleColor:RZ_COLOR(155, 155, 155) forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        btn.tag = idx;
        [btn addTarget:self action:@selector(topBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.topScrollView addSubview:btn];
        [self.topBtns addObject:btn];
    }];
    
    //指示条
    UIView *indicatorBar = [UIView new];
    _indicatorBar = indicatorBar;
    indicatorBar.backgroundColor = RZ_COLOR(254, 220, 69);
    indicatorBar.layer.cornerRadius = 1.5;
    [self.topScrollView addSubview:indicatorBar];
    [self setupTopViewFrame];
    [self topBtnOnClick:self.topBtns.firstObject];
}


- (void)setupTopViewFrame
{
    [self.topScrollView layoutIfNeeded];
    CGSize size = self.topScrollView.size;
    CGFloat margin = 30;
    [self.topBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull btn, NSUInteger idx, BOOL * _Nonnull stop) {
        [btn sizeToFit];
        CGFloat x =0;
        if(idx == 0){
            x= 20;
        }else{
            x= CGRectGetMaxX(self.topBtns[idx-1].frame)+margin;
        }
        btn.frame = CGRectMake(x, 0, btn.width, size.height);
    }];
    self.topScrollView.contentSize = CGSizeMake(CGRectGetMaxX(self.topBtns.lastObject.frame), 0);
}




- (void)topBtnOnClick:(UIButton *)btn
{
    _type_index = btn.tag;
    _last_btn.selected = !_last_btn.isSelected;
    btn.selected = !btn.isSelected;
    _last_btn = btn;
    
    _indicatorBar.frame = CGRectMake(btn.x, self.topScrollView.height-3, btn.width, 3);
    
    if(!self.taskList[@(btn.tag).stringValue]){
        if(btn.tag < self.taskCategory.count){
            NSInteger category_id = [self.taskCategory[btn.tag][@"id"] integerValue];
            [self fetchCategoryListWithCategory_id:category_id];
        }
    }else{
        [self.tableView reloadData];
    }
}




#pragma mark--获取分类列表数据
- (void)fetchCategoryListWithCategory_id:(NSInteger)category_id
{
    HelenParametersDic *dict = [HelenParametersDic h_dictionary];
    /**
    http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live&ac=member&op=task&m=bz_activities&token=87ffec5d746e139250f2da176caff727&ta=index
     
     category 任务分类
     */
    dict[@"ctrl"] = @"live";
    dict[@"ac"] = @"member";
    dict[@"op"] = @"task";
    dict[@"ta"] = @"index";
    dict[@"category"] = @(category_id);
    dict[@"token"] = [RZ_USERDEFAULTES objectForKey:USER_INFO][@"token"];
    
    [HelenHttpClient requestWithUrlString:BASE_URL andParam:dict andMethod:@"POST" progress:nil success:^(id responseObject) {
        
        NSDictionary *res = responseObject[@"message"];
        NSInteger code = [res[@"resultCode"] integerValue];
        if(code== 0 || code ==1){
             self.taskList[@(self.type_index).stringValue] = res[@"data"];
             [self.tableView reloadData];
        }
        
    } andFailBlock:^(NSInteger ErrorCode, NSError *ErrorString) {
        
    }];
}



#pragma mark-- setter&&getter

- (NSMutableArray<UIButton *> *)topBtns
{
    if(!_topBtns){
        _topBtns = [NSMutableArray array];
    }
    return _topBtns;
}

- (NSMutableDictionary<NSString *,NSArray *> *)taskList
{
    if(!_taskList){
        _taskList = [NSMutableDictionary dictionary];
    }
    return _taskList;
}

@end
